package com.leilei.controller;

import com.leilei.entity.Location;
import com.leilei.entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author lei
 * @create 2022-04-07 16:04
 * @desc
 **/
@RestController
@RequestMapping("/location")
public class TestLocationController {
    @Value("${spring.cloud.nacos.discovery.ip}")
    private String ip;
    @Value("${server.port}")
    private Integer port;

    @GetMapping("/last/{vehicleId}")
    public Result<Location> getLocationByVehicleId(@PathVariable("vehicleId") Integer vehicleId) throws Exception {
        Location location = new Location();
        location.setVehicleId(vehicleId);
        location.setPlate("川A0" + vehicleId);
        location.setLatitude(100023);
        location.setLongitude(2345);
        location.setClientInfo(ip + ":" + port);
        // 模拟睡眠4-10s,测试上游消费者读取时间是否生效
        Random random = new Random();
        int j = random.nextInt(7) + 4;
        Thread.sleep(j * 1000);
        return Result.success(location);
    }

    /**
     * 测试响应压缩
     * @param vehicleId
     * @return 默认对返回自定义对象 且是 application/json 无效 ，需要结合Filter 进行处理（返回数据体长度）
     * @throws Exception
     */
    @GetMapping("/date/{vehicleId}")
    public Result<List<Location>> getLocationByVehicle(@PathVariable("vehicleId") Integer vehicleId) throws Exception {
        List<Location> locations = new ArrayList<>();
        for (int i = 0; i < 20000; i++) {
            Location location = new Location();
            location.setVehicleId(vehicleId);
            location.setPlate("川A0" + vehicleId);
            location.setLatitude(100023);
            location.setLongitude(2345);
            location.setClientInfo(ip + ":" + port);
            locations.add(location);
        }
        return Result.success(locations);
    }

    @GetMapping("/test/header")
    public Result<Map<String, String>> testRequestHeader(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return Result.success(map);
    }
}
